<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
      
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="客户">
            <a-select
              show-search
                placeholder="请选择"
                style="width: 100%"
                :filter-option="false"
                :not-found-content="fetching ? undefined : null"
                @search="getcusIdOptions"
                @change="handleChangeCus"
                v-decorator="['cusId', { rules: [{ required: true, message: '请选择客户!' }] }]"
              >
            <a-select-option v-for="t in cusIdOptions" :key="t.value">{{t.text}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="产品">
          <pro-select type=1 v-decorator="['productId', { rules: [{ required: true, message: '请选择产品!' }] }]"/>
        </a-form-item>
        <a-form-item :labelCol="labelCol"  :wrapperCol="wrapperCol" label="销售">
          <j-dict-select-tag v-decorator="['userId', { rules: [{ required: true, message: '请选择用户!' }]}]"
           placeholder="请选择用户" :triggerChange=true dictCode="sys_user,realname,id,sales=1"/>
        </a-form-item>
       <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="销售价格">
         <a-input-number v-model="model.price" />元
       </a-form-item>
       <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="定金价格">
         <a-input-number v-model="model.prePrice" />元
       </a-form-item>
       <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="尾款价格">
         <a-input-number v-model="model.afterPrice" />元
       </a-form-item>
       <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="施工日期">
         <j-date v-decorator="[ 'workingTime', {}]"></j-date>
       </a-form-item>
       <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注">
         <a-textarea v-decorator="[ 'remark', {}]"></a-textarea>
       </a-form-item>
		
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
  import { httpAction,getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from "moment"
  import debounce from 'lodash/debounce';
  import ProSelect from '@/views/crm/comp/ProSelect'
  import JDate from '@/components/jeecg/JDate'

  export default {
    name: "CusOrderSingle",
    components:{
      ProSelect,
      JDate,
    },
    data () {
      this.lastFetchId = 0;
      this.getcusIdOptions = debounce(this.getcusIdOptions, 800);
      return {
        cusIdOptions:[],
        productIdOptions:[],
        fetching:false,
        title:"操作",
        visible: false,
        model: {
          price: 0,
          prePrice: 0,
          afterPrice: 0,
          perfPrice:0,
          rate: 0,
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
        },
        url: {
          add: "/crm/orderSingle/add",
          edit: "/crm/orderSingle/edit",
          getcusId: "/crm/cus/getcusId",
          getproductId: "/crm/product/getproductId",
        },
      }
    },
    created () {
      this.getcusIdOptions();
    },
    computed: {
      getPrice: function() {
        return this.model.price;
      },
      getPrePrice: function() {
        return this.model.prePrice;
      },
    
    },
    watch: {
      getPrice: {
        handler: function() {
          this.culPrice();
        }
      },
      getPrePrice: {
        handler: function() {
          this.culPrice();
        }
      }
    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.model.cusId=record.id;
        this.model.userId=record.ownerUserId;
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'productId','userId','cusId','price','createId'))
		  //时间格式化
        });

      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            httpurl+=this.url.add;
            method = 'post';
            let formData = Object.assign(this.model, values);
            //时间格式化
            
            console.log(formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
      filterOption(input, option) {
        return (
         option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      culPrice() {
        if (this.model.price != undefined && this.model.prePrice != undefined) {
          this.model.afterPrice = this.model.price - this.model.prePrice;
        } else {
          this.model.afterPrice = 0;
        }
      },
      getSaleId(value){
        let param={id:value};
        getAction('/crm/cus/getSaleId', param).then((res) => {
            if (res.success) {
              this.model.userId=res.result;
              this.form.setFieldsValue(pick(this.model,'userId'))
            } else {
              that.$message.warning(res.message)
            }
          
          })
      },
      handleChangeCus(value) {
        console.log(`selected ${value}`);
        this.getSaleId(value);
      },
      getcusIdOptions(value){
        console.log('getcusIdOptions', value);
        this.lastFetchId += 1;
        const fetchId = this.lastFetchId;
        this.cusIdOptions = [];
        this.fetching = true;
        let param={mobile:value};
        getAction(this.url.getcusId, param)
          .then((res) => {
            if (fetchId !== this.lastFetchId) {       
              return;
            }
            if (res.success) {
             this.cusIdOptions=res.result;
            } else {
              that.$message.warning(res.message)
            }
            this.fetching = false;
          })
      },
      
    }
  }
</script>

<style lang="less" scoped>

</style>